<template>
  <div class="live-container">
    <!-- 主播放区 -->
    <div class="main-area">
      <div class="player-wrapper">
        <iframe
          ref="mainPlayer"
          :src="currentVideo.url"
          frameborder="0"
          allowfullscreen
          @load="initPlayer"
          allow="autoplay"
        ></iframe>

        <!-- 弹幕层 -->
        <div class="danmu-layer" ref="danmuLayer"></div>

        <!-- 自定义覆盖层控制按钮 -->
        <div class="custom-controls">
          <button @click="togglePlay" class="play-btn">
            {{ isPlaying ? '❚❚' : '▶' }}
          </button>
        </div>
      </div>

      <!-- 视频控制栏 -->
      <div class="control-bar">
        <button @click="togglePlay">{{ isPlaying ? '暂停' : '播放' }}</button>
        <input
          type="range"
          v-model="progress"
          min="0"
          max="100"
          @input="seekVideo"
          @change="seekVideo"
        >
        <span>{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</span>
        <button @click="toggleFullscreen">全屏</button>
      </div>
    </div>

    <!-- 右侧互动区 -->
    <div class="interaction-area">
      <!-- 视频列表 -->
      <div class="video-list">
        <div
          v-for="(video, index) in videos"
          :key="index"
          class="video-thumb"
          :class="{ active: currentIndex === index }"
          @click="switchVideo(index)"
        >
          <img :src="video.cover" :alt="video.title">
          <div class="video-info">
            <h4>{{ video.title }}</h4>
            <p>{{ video.views }}观看 · {{ video.duration }}</p>
          </div>
        </div>
      </div>

      <!-- 聊天室 -->
      <div class="chat-room">
        <div class="chat-messages" ref="chatMessages">
          <div
            v-for="(msg, index) in chatMessages"
            :key="index"
            class="message"
            :class="{
              'system-msg': msg.type === 'system',
              'gift-msg': msg.type === 'gift'
            }"
          >
            <span class="username" :style="{ color: msg.color }">{{ msg.username }}</span>
            <span class="content">{{ msg.content }}</span>
            <span v-if="msg.gift" class="gift">🎁 {{ msg.gift }}</span>
          </div>
        </div>

        <div class="chat-input">
          <input
            v-model="chatText"
            placeholder="发个弹幕呗~"
            @keyup.enter="sendDanmu"
          >
          <button @click="sendDanmu">发送</button>
          <button class="gift-btn" @click="showGiftPanel">🎁</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
//图片引入
import img1 from '@/assets/imgs/living_video/image1.png'
import img2 from '@/assets/imgs/living_video/image2.png'
import img3 from '@/assets/imgs/living_video/image3.png'
import img4 from '@/assets/imgs/living_video/image4.png'
import img5 from '@/assets/imgs/living_video/image5.png'

export default {
  data() {
    return {
      currentIndex: 0,
      isPlaying: false,
      progress: 0,
      currentTime: 0,
      duration: 0,
      chatText: '',
      chatMessages: [
        {
          username: '系统消息',
          content: '欢迎来到直播间！',
          type: 'system',
          color: '#FF9800'
        },
        {
          username: '哈基米',
          content: 'H100 follow一天啊',
          type: 'normal',
          color: '#4CAF50'
        },
        {
          username: '用户1100',
          content: '这不是主站啊？',
          type: 'normal',
          color: '#2196F3'
        },
        {
          username: '礼物使者',
          content: '送出了',
          type: 'gift',
          color: '#E91E63',
          gift: '小电视'
        }
      ],
      videos: [
        {
          title: '切片大赛直播',
          url: '//player.bilibili.com/player.html?bvid=BV1DuKJzzE25&autoplay=0',
          cover: img1,
          views: '1.2万',
          duration: '5:22'
        },
        {
          title: '满清乐专场',
          url: '//player.bilibili.com/player.html?bvid=BV14AKazAE6i&autoplay=0',
          cover: img2,
          views: '8千',
          duration: '3:45'
        },
        {
          title: 'BEAUTY秀场',
          url: '//player.bilibili.com/player.html?bvid=BV17LK8zjEE5&autoplay=0',
          cover: img3,
          views: '2.5万',
          duration: '6:30'
        },
        {
          title: '满清乐专场',
          url: '//player.bilibili.com/player.html?bvid=BV14AKazAE6i&autoplay=0',
          cover: img4,
          views: '8千',
          duration: '3:45'
        },
        {
          title: 'BEAUTY秀场',
          url: '//player.bilibili.com/player.html?bvid=BV17LK8zjEE5&autoplay=0',
          cover: img5,
          views: '2.5万',
          duration: '6:30'
        }
      ],
      danmuInterval: null,
      videoInterval: null,
      player: null
    }
  },
  computed: {
    currentVideo() {
      return this.videos[this.currentIndex]
    }
  },
  methods: {
    initPlayer() {
      // 获取iframe中的player对象
      this.player = this.$refs.mainPlayer.contentWindow.document.querySelector('video');

      if (this.player) {
        // 监听视频时间更新
        this.player.addEventListener('timeupdate', this.updateProgress);
        // 监听视频结束
        this.player.addEventListener('ended', this.videoEnded);

        this.duration = this.player.duration || 360; // 默认6分钟
        this.startDanmu();
      } else {
        console.warn('无法获取视频播放器对象');
        this.duration = 360; // 模拟6分钟视频
        this.startVideoProgress();
        this.startDanmu();
      }
    },
    updateProgress() {
      if (this.player) {
        this.currentTime = this.player.currentTime;
        this.progress = (this.currentTime / this.duration) * 100;
      }
    },
    videoEnded() {
      this.isPlaying = false;
    },
    togglePlay() {
      if (this.player) {
        if (this.player.paused) {
          this.player.play().then(() => {
            this.isPlaying = true;
          }).catch(e => {
            console.error('播放失败:', e);
            // 如果自动播放被阻止，显示播放按钮让用户手动触发
            this.isPlaying = false;
          });
        } else {
          this.player.pause();
          this.isPlaying = false;
        }
      } else {
        // 模拟播放/暂停
        this.isPlaying = !this.isPlaying;
        if (this.isPlaying) {
          this.startVideoProgress();
        } else {
          clearInterval(this.videoInterval);
          this.videoInterval = null;
        }
      }
    },
    startVideoProgress() {
      if (this.videoInterval) clearInterval(this.videoInterval);

      this.videoInterval = setInterval(() => {
        if (this.isPlaying && this.currentTime < this.duration) {
          this.currentTime++;
          this.progress = (this.currentTime / this.duration) * 100;
        }
      }, 1000);
    },
    seekVideo(e) {
      const seekTime = (e.target.value / 100) * this.duration;
      this.currentTime = seekTime;

      if (this.player) {
        this.player.currentTime = seekTime;
      }
    },
    startDanmu() {
      const danmus = [
        '罗生门啊',
        '提前领好吧',
        '李妈',
        '受波唱的我头是',
        '导演们好听捏',
        '1100',
        '有点影响观感',
        '1~2保底1100',
        '龙江记今天又没了'
      ];

      this.danmuInterval = setInterval(() => {
        const randomDanmu = danmus[Math.floor(Math.random() * danmus.length)];
        this.showDanmu(randomDanmu);
      }, 2000);
    },
    showDanmu(text) {
      const danmu = document.createElement('div');
      danmu.className = 'danmu';
      danmu.textContent = text;
      danmu.style.top = `${Math.random() * 80 + 10}%`;
      danmu.style.color = `hsl(${Math.random() * 360}, 100%, 70%)`;

      this.$refs.danmuLayer.appendChild(danmu);

      setTimeout(() => {
        danmu.remove();
      }, 5000);
    },
    switchVideo(index) {
      this.currentIndex = index;
      this.resetPlayer();

      // 重新加载iframe
      this.isPlaying = false;
      this.currentTime = 0;
      this.progress = 0;

      // 重置播放器
      this.$nextTick(() => {
        this.initPlayer();
      });
    },
    resetPlayer() {
      this.currentTime = 0;
      this.progress = 0;
      this.isPlaying = false;
    },
    toggleFullscreen() {
      const elem = this.$refs.mainPlayer;
      if (!document.fullscreenElement) {
        elem.requestFullscreen().catch(err => {
          console.error(`全屏错误: ${err.message}`);
        });
      } else {
        document.exitFullscreen();
      }
    },
    sendDanmu() {
      if (!this.chatText.trim()) return;

      // 添加到聊天室
      this.chatMessages.push({
        username: '我',
        content: this.chatText,
        type: 'normal',
        color: '#FF5722'
      });

      // 显示为弹幕
      this.showDanmu(this.chatText);

      // 滚动到底部
      this.$nextTick(() => {
        this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
      });

      this.chatText = '';
    },
    showGiftPanel() {
      const gifts = ['小电视', '飞机', '火箭', '喵娘'];
      const randomGift = gifts[Math.floor(Math.random() * gifts.length)];

      this.chatMessages.push({
        username: '我',
        content: '送出了',
        type: 'gift',
        color: '#E91E63',
        gift: randomGift
      });

      this.$nextTick(() => {
        this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
      });
    },
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
    }
  },
  beforeUnmount() {
    clearInterval(this.danmuInterval);
    clearInterval(this.videoInterval);
    if (this.player) {
      this.player.removeEventListener('timeupdate', this.updateProgress);
      this.player.removeEventListener('ended', this.videoEnded);
    }
  }
}
</script>

<style scoped lang="scss">
.live-container {
  display: flex;
  height: 100vh;
  background-image: url('@/assets/imgs/living_video/img_bg.png');
  font-family: "Microsoft YaHei", sans-serif;
}

.main-area {
  flex: 3;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.player-wrapper {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%; /* 16:9 比例 */
  background: #000;
  border-radius: 8px;
  overflow: hidden;

  iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: none;
  }

  .custom-controls {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    display: flex;
    justify-content: center;
    align-items: center;

    .play-btn {
      pointer-events: auto;
      width: 60px;
      height: 60px;
      border-radius: 50%;
      background: rgba(0, 0, 0, 0.6);
      color: white;
      border: none;
      font-size: 24px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      transition: all 0.3s;
      opacity: 0;

      &:hover {
        background: rgba(0, 0, 0, 0.8);
        transform: scale(1.1);
      }
    }

    &:hover .play-btn {
      opacity: 1;
    }
  }
}

.danmu-layer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  overflow: hidden;
}

.danmu {
  position: absolute;
  right: 0;
  white-space: nowrap;
  font-size: 18px;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.8);
  animation: danmuMove 5s linear forwards;
}

@keyframes danmuMove {
  from { transform: translateX(100%); }
  to { transform: translateX(-100%); }
}

.control-bar {
  display: flex;
  align-items: center;
  padding: 10px;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 0 0 8px 8px;
  margin-top: -8px;
  display: none;

  button {
    background: #fb7299;
    color: white;
    border: none;
    padding: 5px 10px;
    margin-right: 10px;
    border-radius: 4px;
    cursor: pointer;

    &:hover {
      background: #f55f8a;
    }
  }

  input[type="range"] {
    flex: 1;
    margin: 0 10px;
  }

  span {
    color: white;
    font-size: 14px;
    min-width: 100px;
    text-align: center;
  }
}

.interaction-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.video-list {
  margin-bottom: 20px;

  .video-thumb {
    display: flex;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s;
    background: rgba(0, 0, 0, 0.05);
    opacity: 0.8;

    &:hover {
      background: rgba(0, 0, 0, 0.1);
      opacity: 1;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    &.active {
      opacity: 1;
      .video-info {
        h4 {
          color: #000;
          font-weight: bold;
        }
        p {
          color: #666;
        }
      }
    }

    img {
      width: 80px;
      height: 45px;
      border-radius: 4px;
      object-fit: cover;
      margin-right: 10px;
      transition: all 0.3s;
      filter: brightness(0.9);
    }

    &:hover img,
    &.active img {
      border: 3px solid #2196f3;
      box-shadow: 0 2px 12px rgba(33, 150, 243, 0.2);
    }

    .video-info {
      flex: 1;

      h4 {
        margin: 0 0 5px 0;
        font-size: 14px;
        color: #555;
        transition: all 0.3s;
      }

      p {
        margin: 0;
        font-size: 12px;
        color: #888;
        transition: all 0.3s;
      }
    }
  }
}

.chat-room {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  background: #f9f9f9;

  .message {
    margin-bottom: 10px;
    line-height: 1.4;
    word-break: break-word;

    .username {
      font-weight: bold;
      margin-right: 5px;
    }

    .gift {
      color: #e91e63;
      margin-left: 5px;
    }

    &.system-msg {
      color: #ff9800;
      font-size: 12px;
      text-align: center;
    }

    &.gift-msg {
      color: #e91e63;
      animation: giftHighlight 1s;
    }
  }
}

@keyframes giftHighlight {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.chat-input {
  display: flex;
  padding: 10px;
  background: white;
  border-top: 1px solid #eee;

  input {
    flex: 1;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    outline: none;

    &:focus {
      border-color: #fb7299;
    }
  }

  button {
    background: #fb7299;
    color: white;
    border: none;
    padding: 0 15px;
    margin-left: 10px;
    border-radius: 4px;
    cursor: pointer;

    &:hover {
      background: #f55f8a;
    }
  }

  .gift-btn {
    background: #ff9800;

    &:hover {
      background: #f57c00;
    }
  }
}
</style>
